import time
import logging
import sys
from config import GB28181Config
from sip_client import SIPClient
from media_handler import MediaStreamer
from command_processor import CommandProcessor
from device_controller import DeviceController

# 配置日志
logging.basicConfig(
    level=logging.DEBUG,  # 更详细的日志级别
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    stream=sys.stdout
)

def main():
    try:
        # 初始化配置
        config = GB28181Config()
        logger = logging.getLogger('Main')
        
        # 创建核心组件
        sip_client = SIPClient(config)
        media_streamer = MediaStreamer(config)
        device_controller = DeviceController(config)
        command_processor = CommandProcessor(sip_client, media_streamer, device_controller)
        
        # 设置消息处理器
        sip_client.set_message_handler(command_processor.handle_message)
        
        # 注册并启动
        if sip_client.register(max_retries=5):  # 增加重试次数
            logger.info("注册成功！")
            
            # 启动SIP监听线程
            sip_client.start()
            
            # 等待一下让SIP监听启动
            time.sleep(2)
            
            #新增
            # 主动发送目录通知
            logger.info("发送目录通知...")
            sip_client.send_catalog_notify()
            
            # 主循环
            try:
                while True:
                    time.sleep(1)
            except KeyboardInterrupt:
                logger.info("正在关闭...")
                sip_client.stop()
        else:
            logger.error("注册失败，退出程序")
            
    except Exception as e:
        logger.error(f"致命错误: {str(e)}")
        return 1
    
    return 0

if __name__ == "__main__":
    exit(main())